<?php
class Server {
  public static function submit_obj($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    
    if ($req->start == '') {
      echo 'Start is empty';
      return;
    }
    
    if ($req->end == '') {
      echo 'End is empty';
      return;
    }
    
    if (isset($req->id) && $req->id != -1) {
      $orm->update('pb_colg_intake', $req);
    } else {
      $orm->add('pb_colg_intake', $req);
      $req->id = $orm->last_id();
    }
    
    if (isset($req->__pg)) {
      $opts = new stdClass();
      $opts->cd = 't.type = :v1';
      $opts->cdv = array(':v1' => PT_NCEA);
      $req->__objs = $orm->get('pb_colg_intake', 't.start', 'ASC', $req->__pg, SIZE, $opts);
    }
    
    echo json_encode($req);
  }
  
  public static function get_obj($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    
    $opts = new stdClass();
    $opts->cd = 't.id = :v1';
    $opts->cdv = array(':v1' => $req->id);
    $res = $orm->get('pb_colg_intake', NULL, NULL, NULL, NULL, $opts)->d;
    if (count($res) > 0) {
      $opts = new stdClass();
      $opts->cd = 't.intake_id = :v1';
      $opts->cdv = array(':v1' => $res[0]->id);
      $res['__data'] = $orm->get('pb_colg_class', 't.name', 'ASC', NULL, NULL, $opts)->d;
      foreach ($res['__data'] as $itm) {
        $itm->times = json_decode($itm->times);
      }
    }
    
    echo json_encode($res);
  }
  
  public static function submit_class($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    if ($req->name == '') {
      echo 'Name is empty';
      return;
    }
    
    sort($req->times); 
    $req->times = json_encode($req->times);
    if (isset($req->id)) {
      $orm->update('pb_colg_class', $req);
    } else {
      $orm->add('pb_colg_class', $req);
      $req->id = $orm->last_id();
      $req->times = json_decode($req->times);
    }
    echo json_encode($req);
  }
  
  public static function delete_class($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    $orm->delete('pb_colg_class', $req);
  }
}
?>